package cn.iocoder.yudao.module.infra.llm;

import cn.iocoder.yudao.module.infra.llm.impl.proxy.LLMServiceCacheProxy;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class LLMServiceFactory {
    private final Map<String, ILLMService> serviceMap = new HashMap<>();
    @Resource
    private LLMConfig llmConfig;
    @Resource
    private LLMServiceCacheProxy cacheProxy;

    @Autowired
    public LLMServiceFactory(Map<String, ILLMService> map) {
        this.serviceMap.putAll(map);
    }

    @PostConstruct
    public void init() {
        log.info("初始化LLM服务, primary = {}", llmConfig.getPrimary());
    }

    public ILLMService getService() {
        final String primary = llmConfig.getPrimary();
        final ILLMService rawService = serviceMap.get("llm-" + primary);

        if (!llmConfig.getCache()) {
            return rawService;
        }

        // 使用缓存代理包装原始服务
        cacheProxy.setTargetService(rawService);
        return cacheProxy;
    }
}
